package com.ysstech.system.controller;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ysstech.common.annotation.YssLog;
import com.ysstech.common.annotation.YssPermissions;
import com.ysstech.common.config.UploadFileConfig;
import com.ysstech.common.entity.Dicvalue;
import com.ysstech.common.entity.TreeNode;
import com.ysstech.common.controller.BaseController;
import com.ysstech.common.encryption.SM3Utils;
import com.ysstech.common.entity.Role;
import com.ysstech.common.entity.User;
import com.ysstech.common.exception.BusinessException;
import com.ysstech.common.util.DateUtil;
import com.ysstech.common.util.resultutil.RestResult;
import com.ysstech.common.util.resultutil.ResultGenerator;
import com.ysstech.system.entity.UserRole;
import com.ysstech.system.enums.SystemEnum;
import com.ysstech.system.service.RoleService;
import com.ysstech.system.service.OrganizationService;
import com.ysstech.system.service.UserRoleService;
import com.ysstech.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@Slf4j
@Api(tags = "用户信息模块api")
@RequestMapping(value = "/userInfo")
public class UserInfoController extends BaseController {
    @Autowired
    private UserService userService;
    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserRoleService userRoleService;

    @YssPermissions(value = {"system:user"})
    @ApiOperation(value = "跳转用户信息管理页面")
    @YssLog(module = "用户管理", remark = "跳转用户信息管理页面")
    @RequestMapping(value = "/page")
    public String page() throws Exception {
        return "system/user";
    }

    @YssPermissions(value = {"system:user"})
    @ApiOperation(value = "获取角色页面机构的状态的值")
    @YssLog(module = "用户管理", remark = "获取角色页面机构的状态的值")
    @PostMapping(value = "/init")
    @ResponseBody
    public RestResult init() throws Exception {
        String orgId = redisCacheManager.getLoginUserInfo().getOrgId();
        List<TreeNode> listOrganization = organizationService.queryOrganizationTree(orgId);
        List<Dicvalue> sysStatus = dicValueService.getCacheDicValueList(SystemEnum.SYS_STATUS.getCode());
        Map<String, Object> map = new HashMap<>();
        map.put("listOrganization", listOrganization);
        map.put("sysStatus", sysStatus);
        return ResultGenerator.getSuccessResult("获取页面初始化信息成功", map);
    }

    /**
     * 用户列表的方法
     * 查询当前登录人所在机构和所有下级机构用户
     *
     * @return
     */
    @YssPermissions(value = {"system:user"})
    @ApiOperation(value = "获取用户信息列表")
    @YssLog(module = "用户管理", remark = "获取用户信息列表")
    @PostMapping(value = "/listInfo")
    @ResponseBody
    public RestResult listUser(User user, String page, String rows) throws Exception {
        return ResultGenerator.getSuccessResult("获取用户信息列表成功", userService.queryAllUsers(user, this.getPage(page, rows)));
    }


    /**
     * 新增用户的方法
     *
     * @param user
     * @return
     */
    @YssPermissions(value = {"system:user:add"})
    @ApiOperation(value = "新增用户信息")
    @YssLog(module = "用户管理", remark = "新增用户信息")
    @RequestMapping(value = "/addUser")
    @ResponseBody
    public RestResult addUser(User user) throws Exception {
        user.setId(DateUtil.generateUUID());
        user.setPassword(SM3Utils.sm3encrypt(SystemEnum.RESET_PASSWORD.getCode()));
        user.setAddTime(LocalDateTime.now());
        user.setLastModifyTime(LocalDateTime.now());
        user.setLastModify(redisCacheManager.getLoginUserInfo().getLoginId());
        user.setIsFirstLogin(1);
        user.setStatus(1);
        user.setIsLock(2);
        userService.save(user);
        return ResultGenerator.getSuccessResult("新增用户信息成功！");
    }

    /**
     * 修改用户信息
     *
     * @return
     */
    @YssPermissions(value = {"system:user:edit"})
    @ApiOperation(value = "修改用户信息")
    @YssLog(module = "用户管理", remark = "修改用户信息")
    @RequestMapping(value = "/editUser")
    @ResponseBody
    public RestResult editUser(User user) throws Exception {
        User userLoginInfo = redisCacheManager.getLoginUserInfo();
        if (user == null || StringUtils.isBlank(user.getId())) {
            throw new BusinessException("获取用户信息失败，请稍后重试！");
        }
        user.setLastModify(userLoginInfo.getName());
        user.setLastModifyTime(LocalDateTime.now());
        userService.updateById(user);
        return ResultGenerator.getSuccessResult("修改用户信息成功！");
    }

    /**
     * 删除用户信息
     *
     * @return
     */
    @YssPermissions(value = {"system:user:del"})
    @ApiOperation(value = "删除用户信息")
    @YssLog(module = "用户管理", remark = "删除用户信息")
    @RequestMapping(value = "/delUser")
    @ResponseBody
    public RestResult delUser(String ids) throws Exception {
        if (StringUtils.isBlank(ids)) {
            throw new BusinessException("获取删除用户信息失败，请稍后重试！");
        }
        List<String> list = JSONArray.parseArray(ids, String.class);
        userService.batchDeleteUser(list);
        return ResultGenerator.getSuccessResult("删除用户信息成功！");
    }

    /**
     * 锁定或者解锁用户
     *
     * @param userarry
     * @return
     */
    @YssPermissions(value = {"system:user:lock", "system:user:unlock"}, logical = Logical.AND)
    @ApiOperation(value = "锁定解锁用户信息")
    @YssLog(module = "用户管理", remark = "锁定解锁用户信息")
    @RequestMapping(value = "/updateIsLock")
    @ResponseBody
    public RestResult updateIsLock(String userarry) throws Exception {
        if (StringUtils.isBlank(userarry)) {
            throw new BusinessException("获取用户信息失败，请稍后重试！");
        }
        List<User> list = JSONArray.parseArray(userarry, User.class);
        userService.updateIsLock(list);
        return ResultGenerator.getSuccessResult("锁定解锁用户信息成功！");
    }


    @YssPermissions(value = {"system:user:export"})
    @ApiOperation(value = "导出用户信息")
    @YssLog(module = "用户管理", remark = "导出用户信息")
    @RequestMapping("/userexport")
    @ResponseBody
    public RestResult userexport(HttpServletResponse response, User user) throws Exception {
        log.info("登陆信息导出开始------------------------");
        userService.userexport(response, user);
        return ResultGenerator.getSuccessResult("导出用户信息成功！");
    }

    @YssPermissions(value = {"system:user:role"})
    @ApiOperation(value = "获取用户角色列表信息")
    @YssLog(module = "用户管理", remark = "获取用户角色列表信息")
    @RequestMapping(value = "/queryRoleListByOrgId")
    @ResponseBody
    public RestResult queryRoleListByOrgId(String orgId, String userId) throws Exception {
        Map<String, Object> map = new HashMap<>();
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.eq("ORG_ID", orgId);
        List<Role> pageRole = roleService.list(wrapper);
        map.put("rows", roleService.switchedListRole(pageRole));
        QueryWrapper<UserRole> wrapperUserRole = new QueryWrapper<>();
        wrapperUserRole.eq("USER_ID", userId);
        List<UserRole> listRoleId = userRoleService.list(wrapperUserRole);
        map.put("listRoleId", listRoleId);
        return ResultGenerator.getSuccessResult("获取机构下所有角色信息成功", map);
    }

    /**
     * 保存用户的角色信息方法
     *
     * @param userrolearry
     * @return
     */
    @YssPermissions(value = {"system:user:role"})
    @ApiOperation(value = "保存用户的角色信息")
    @YssLog(module = "用户管理", remark = "保存用户的角色信息")
    @RequestMapping(value = "/updateUserRole")
    @ResponseBody
    public RestResult updateUserRole(String userrolearry) throws Exception {
        if (StringUtils.isBlank(userrolearry)) {
            throw new BusinessException("获取用户信息失败，请稍后重试！");
        }
        List<UserRole> list = JSONArray.parseArray(userrolearry, UserRole.class);
        userService.batchInserUserRole(list);
        return ResultGenerator.getSuccessResult("保存用户的角色信息成功！");
    }

    @YssPermissions(value = {"system:user:resetPassword"})
    @ApiOperation(value = "重置用户密码")
    @YssLog(module = "用户管理", remark = "重置用户密码")
    @RequestMapping(value = "/resetPassword")
    @ResponseBody
    public RestResult resetPassword(String ids) throws Exception {
        if (StringUtils.isBlank(ids)) {
            throw new BusinessException("获取需要重置密码的用户信息失败，请稍后重试！");
        }
        List<String> list = JSONArray.parseArray(ids, String.class);
        userService.resetPassword(list);
        return ResultGenerator.getSuccessResult("重置用户密码成功，请用户登录后修改初始密码");
    }

    /**
     * 判断用户登录名称是否已经存在
     *
     * @param newloginId
     * @return
     */
    @ApiOperation(value = "检查用户登录名是否存在")
    @YssLog(module = "用户管理", remark = "检查用户登录名是否存在")
    @RequestMapping(value = "/checkUserLoginId")
    @ResponseBody
    public RestResult checkUserLoginId(String newloginId) {
        if (StringUtils.isBlank(newloginId)) {
            return ResultGenerator.getFailResult("检查用户信息失败，请稍后重试！");
        }
        QueryWrapper<User> wrapperUserRole = new QueryWrapper<>();
        wrapperUserRole.eq("LOGIN_ID", newloginId);
        int count = userService.count(wrapperUserRole);
        //查询是否存在code值得参数
        if (count > 0) {//返回true表示已经存在
            return ResultGenerator.getSuccessResult("检查用户信息成功", false);
        } else {
            return ResultGenerator.getSuccessResult("检查用户信息成功", true);
        }
    }

    @Autowired
    private UploadFileConfig uploadFileConfig;

    //文件上传相关代码
    @ApiOperation(value = "用户头像上传")
    @YssLog(module = "用户管理", remark = "用户头像上传")
    @RequestMapping("/image/upload")
    @ResponseBody
    public RestResult uploadImage(MultipartFile file, String oldImageId) throws Exception {
        //  String path = ImageUploadUtil.uploadImage(file, oldImageId);
        // handler**调用文件上传的service 得到文件的虚拟路径*
        String filepath = uploadFileConfig.uploadImg(file);
        return ResultGenerator.getSuccessResult("上传图片成功！", filepath);
    }

    /**
     * 修改用户密码的方法
     *
     * @param oldPassword
     * @param newPassword
     * @param affirmPassword
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "修改密码的方法")
    @YssLog(module = "用户管理", remark = "修改密码的方法")
    @RequestMapping(value = "/updateUserPassword")
    @ResponseBody
    public RestResult updateUserPassword(String oldPassword, String newPassword, String affirmPassword) throws Exception {
        userService.updateUserPassword(oldPassword, newPassword, affirmPassword);
        return ResultGenerator.getSuccessResult("尊敬的用户,密码修改成功,请重新登录系统！");
    }


    @ApiOperation(value = "测试定时任务")
    @YssLog(module = "用户管理", remark = "测试定时任务")
    @RequestMapping("/schedule/test")
    @ResponseBody
    public RestResult scheduleTest(String code) throws Exception {
        log.info("进入定时任务接口" + code);
        return ResultGenerator.getSuccessResult("定时任务启动成功！");
    }
}
